﻿CREATE PROCEDURE [dbo].[LedgerSubcontoTypesInsert]
(--список субконто для типов проводок
	@Name varchar(100),
	@Note varchar(250),
	@MD datetime OUTPUT,
	@MW varchar(50) OUTPUT,
	@Id int OUTPUT
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intNextId int
SET NOCOUNT ON

IF (@Name Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF (ltrim(@Name) = '')
BEGIN
	SELECT @intErrCode = 2, @strMsg = 'Незаполнено наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF EXISTS (SELECT TOP 1 ID FROM [CO].LedgerSubcontoTypes WHERE Name = @Name AND ToDelete = 0) 
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Дублируется наименование!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF NOT EXISTS (SELECT DepartmentId FROM PR.DepartmentOptions WHERE DepartmentId = 0 ) 
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Изменять данные спрвочников можно только в офисе!'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CO].LedgerSubcontoTypes (Id, [Name], [Note], [MD], [MW], ToDelete) 
VALUES ( @intNextId, @Name, @Note, @MD, @MW, 0);
	
--SELECT Id, Name, Note, MD, MW, ToDelete FROM CO.LedgerSubcontoTypes WHERE (Id = @intNextId)
SELECT @Id = @intNextId

RETURN 0
